package service

import (
	"fmt"
	"haiqiu-go-admin/config"
	"haiqiu-go-admin/dao"
	"haiqiu-go-admin/entity"
	"io"
	"io/fs"
	"log"
	"net/http"
	"os"
	"path"
	"strings"
	"time"
)

func ConfigSelectByPrimaryKey(id int) (entity.SysConfig, error) {
	sysConfig, err := dao.ConfigSelectByPrimaryKey(id)
	if err != nil {
		return sysConfig, err
	}
	return sysConfig, nil
}

func SystemConfigUpdate(sysConfig *entity.SysConfig) (int64, error) {
	sysConfig.UpdateTime = time.Now()
	sysConfig.Id = 1
	lastId, err := dao.SysConfigUpdateById(sysConfig)
	if err != nil {
		log.Println(err.Error())
		return 0, err
	}
	return lastId, nil
}

func UploadTheme(w http.ResponseWriter, r *http.Request) (any, error) {
	file, header, err := r.FormFile("file")
	if err != nil {
		return nil, err
	}
	defer file.Close()

	fileNameAll := path.Base(header.Filename)
	fileSuffix := path.Ext(fileNameAll)
	//filePrefix := fileNameAll[0 : len(fileNameAll)-len(fileSuffix)]
	split := "/theme/system/"
	newFileName := fmt.Sprintf("%d%v", time.Now().UnixMilli(), fileSuffix)
	filePath := fmt.Sprintf("%v", config.AppConfig.Http.Parent) + split + newFileName
	err = os.MkdirAll(fmt.Sprintf("%v", config.AppConfig.Http.Parent)+split, fs.ModeDir)
	if err != nil {
		return nil, err
	}
	dst, err := os.Create(filePath)
	if err != nil {
		return nil, err
	}
	defer dst.Close()
	_, err = io.Copy(dst, file)
	if err != nil {
		return nil, err
	}
	var url = fmt.Sprintf("%v", config.AppConfig.Http.Server)
	suffix := fmt.Sprintf("%v", config.AppConfig.Http.Virtual) + split +
		newFileName
	replaceAll := strings.ReplaceAll(suffix, "//", "/")
	return url + replaceAll, nil
}
